<template>
  <base-page-view class-name="page-container">
    <view class="main">
      <base-nav title="" class="boxDetails_nav">
        <template slot="left" >
          <image class="header-left" src="/static/images/icon/icon_arror_left.png" @click="back()"/>
        </template>
        <template slot="title">
          <view class="title-nav">会员升级礼包</view>
        </template>
        <template slot="right">
          <view class="header-right" @click="$navigateTo('/pagesMember/payHistory/index')">购买记录</view>
        </template>
      </base-nav>
      <view class="head-box">
        <view class="left-box">
          <!-- <b-image :src="$store.state.userInfo.head_img" is-head width="60" height="60" class-name="user-icon" /> -->
          <text>{{detailInfo.title}}</text>
        </view>
        <view class="right-box">￥{{detailInfo.money||''}}元{{detailInfo.upgrade_time?'/'+detailInfo.upgrade_time:''}}{{detailInfo.upgrade_time_unit|memberUnit}}</view>
      </view>
      <view class="shangpin-box content-box" v-if="detailInfo.one_of_n_coupon_goods_v_o_s&&detailInfo.one_of_n_coupon_goods_v_o_s.length>0">
        <view class="title-box">请选择商品礼包</view>
        <view class="good-content">
          <view class="good-box" v-for="(item,index) in detailInfo.one_of_n_coupon_goods_v_o_s" :key="index" >
            <view class="img-box" @click="go_goods(item)">
              <url-image :src="item.goods.pic" mode="widthFix"></url-image>
            </view>
            <view class="info-box" @click="xz_coupon(item,index)">
              <view class="name">{{item.goods.title}}</view>
              <view class="time" v-if="item.coupon_activity_v_o.use_time_type === 'BY_DAYS' && item.coupon_activity_v_o.use_days">
                有效期: 领取后{{ item.coupon_activity_v_o.use_days }}天内有效
              </view>
              <view class="time" v-else>{{item.coupon_activity_v_o.use_start_time|formatDate("yyyy.MM.dd")}}-{{item.coupon_activity_v_o.use_stop_time|formatDate("yyyy.MM.dd")}}</view>
              <!-- <view class="price">￥{{item.goods.price|formatMoney}}</view> -->
            </view>
            <view class="select-box" @click="xz_coupon(item,index)">
              <url-image v-if="String(index)===String(couponIndex)" src="/static/images/member/pay/select.png" width="36" height="36"></url-image>
              <url-image v-else src="/static/images/member/pay/un-select.png" width="36" height="36"></url-image>
            </view>
          </view>
        </view>
      </view>
      <view class="quanyi-box content-box" v-if="detailInfo.user_privilege_config_v_o_s&&detailInfo.user_privilege_config_v_o_s.length>0">
        <view class="title-box">会员权益</view>
        <view class="qy-content">
          <view class="qy-box" v-for="(item,index) in detailInfo.user_privilege_config_v_o_s" :key="index" @click="go_url(item)">
            <url-image :src="item.icon_url" mode="widthFix" width="80" height="80"></url-image>
            <view class="name">{{item.title}}</view>
          </view>
        </view>
      </view>
      <view class="pay-btn">
        <view class="price-box">
          <text class="txt1">金额：</text>
          <text class="txt2">￥</text>
          <text class="txt3">{{detailInfo.money|formatMoney}}</text>
        </view>
        <view class="btn-box" v-if="detailInfo.remain_buy_times&&detailInfo.remain_buy_times>0" @click.stop.prevent="payment">立即购买</view>
        <view class="btn-box huise" v-else>立即支付</view>
      </view>
      <confirm-popup ref="confirm" :modelClose="false" :hasTimeOut="false"/>
      <pay-dialog ref="payDialog" :order-no="orderNo" @submitCallBack="toPayResult" :skipOrder="false" :payOrderType="1"></pay-dialog>
    </view>
  </base-page-view>
</template>
<script>
import payDialog from '@/components/pay/payDialog.vue'
import { h5NavigateTo, toFunctionDetail, toGoods,toBackPage } from '@/utils/navigateTo'
import { mapState,mapActions } from 'vuex'
let that;
// #ifdef MP-WEIXIN
import { toPay } from '@/utils/tools'
// #endif
	export default {
    components:{
      payDialog
    },
		data() {
			return {
        coupon_id:"",//选择的券
        couponIndex:"",//选择的优惠券位置
        pay_select:"",//选择的支付方式
        memberType:"",//会员卡类型
				memberInfo:{},//会员卡信息
        detailInfo:{},//当前页详情
        orderNo:"",//订单号
        select_item:"",//选择的项目
			}
		},
    filters:{
      memberUnit(value){
        switch (value){
          case 1:
            return "天"
            break;
          case 2:
            return "月"
            break;
          case 3:
            return "季"
            break;
          case 4:
            return "年"
            break;
          case 5:
            return "终身"
            break;
          default:
            return ""
            break;
        }
      },
    },
    computed:{
      memberTitle(){
        let title="";
        if(this.memberType){
          switch (this.memberType.toLocaleLowerCase()){
            case "vip":
              title="VIP";
              break;
            case "diamond":
              title="钻石";
              break;
            default:
              break;
          }
        }
        return title;
      },
      memberCardId(){
        let type="";
        if(this.memberType){
          switch (this.memberType.toLocaleLowerCase()){
            case "vip":
              type=this.memberInfo.upgrade_vip_member_i_d;
              break;
            case "diamond":
              type=this.memberInfo.upgrade_diamond_member_i_d;
              break;
            default:
              break;
          }
        }
        return type;
      },
    },
    onLoad(option) {
      this.memberType=option.type;
      that=this;
    },
    deactivated() {
      this.$setNavTitle('',false);
    },
    onShow() {
      this.$setNavTitle('会员升级礼包',true);
      if(!this.token){
        this.$navigateTo('/pages/login/index');
        return;
      }
      if(this.userInfo.current_member_card_type==3){
        setTimeout(_=>{
          this.$nextTick(()=>{
            this.$refs.confirm.show({
              title: '温馨提示',
              content: `您是碧选董事，享受最高权益不支持购买会员礼包`,
              yesTxt:"会员中心",
              cancleTxt:"返回",
              yesCb: async() => {
                this.$navigateTo("/pagesMember/member/index");
              },
              cancleCb(){
                uni.navigateBack();
              }
            })
          })
        },200);
      }
      this.get_member();
    },
		methods: {
      ...mapActions([
        'GetUserInfo'
      ]),
      back(){
        toBackPage();
      },
      //跳转商品详情
      go_goods(item){
        toGoods(item.goods);
      },
      //优惠券选择
      xz_coupon(item,index){
        console.log(item);
        this.couponIndex=String(index);
        this.coupon_id=item.coupon_activity_v_o.coupon_activity_id;
        this.select_item=item;
      },
      //链接跳转
      go_url(item){
        toFunctionDetail(item);
      },
      //获取会员卡列表
			async get_member(){
			  const res = await this.$api.memberApi.getMyMemberCardInfo();
			  if(res.code===0){
			    this.memberInfo=res.data;
          if(this.memberType){
            this.get_detail();
          }
			  }
			},
      //获取会员卡详情
      async get_detail(){
        const res = await this.$api.memberApi.payMemberCardDetail({
          upgradeMakeMoneyMemberId:this.memberCardId
        });
        if(res.code==0){
          this.detailInfo=res.data;
          if(this.detailInfo.one_of_n_coupon_goods_v_o_s.length>0&&!this.couponIndex){
            this.xz_coupon(this.detailInfo.one_of_n_coupon_goods_v_o_s[0],0);//默认选中第一个
          }
        }
      },
      //下单按钮
      async payment(){
        if(!this.detailInfo.order_no){
          this.$msg("订单id为空");
          return;
        }
        //有订单号先刷新订单再创建
        if(this.orderNo){
          this.$api.memberApi.updateOrderNo({
            orderNo:this.orderNo
          }).then(res=>{
            this.orderPlace(res.data);
          });
        }else{
          this.orderPlace(this.detailInfo.order_no);
        }
      },
      //创建订单
      orderPlace(order){
        let goodsId=this.select_item&&this.select_item.goods?this.select_item.goods.goods_id:'';
        let goodsType=this.select_item&&this.select_item.goods?this.select_item.goods.type:'';
        this.$api.memberApi.setMemberCardOrder({
          couponActivityId:this.coupon_id,
          orderNo:order,
          upgradeMakeMoneyMemberId:this.memberCardId,
          goodsId:goodsId,//单品或者套餐的id
          goodsType:goodsType,//商品类型：1-单品 2-套餐
        }).then(res=>{
          if(res.code===0){
            this.orderNo=res.data;
            // this.payOrder();//直接支付
            // this.toPayResult();
            this.$refs.payDialog.show();//使用弹窗支付
          }
        });
      },
      //支付成功
      async toPayResult(data){
        if(this.select_item){
          uni.setStorageSync('member_pay_select', this.select_item);
        }else{
          uni.removeStorageSync('member_pay_select');
        }
        await this.GetUserInfo();//获取用户信息
        this.$navigateTo('/pagesMember/paySuccess/index?orderNo=' + this.orderNo+'&type='+this.memberType);
      },
      //支付
      async payOrder(){
        if (!this.orderNo) return
        // #ifdef H5
        const type = this.$Bridge.isInWeChat ? '3' : '2'
        if (type === '2') {
          uni.showToast({
            title: '请前往公众号【碧选】去支付',
            icon: 'none',
            duration: 3 * 1000
          })
          if (type === '2') return
        } else if (type === '3') {
          // 公众号支付
          const result = await this.$api.orderApi.orderPay({
            provider: '',
            pay_channel: 3, // type,
            order_no: this.orderNo,
            ip: '0.0.0.0',
            code: '',
            openId: this.userInfo.openId,
            payOrderType:1
          })
          this.onBridgeReady(result.data)
        }
        // #endif
        // #ifdef MP-WEIXIN
          //小程序支付
          uni.login({
            provider: 'weixin',
            success: async res => {
              if (res.errMsg === 'login:ok') {
                const result = await this.$api.orderApi.orderPay({
                  payChannel: 6, // type,
                  orderNo: this.orderNo,
                  ip: '0.0.0.0',
                  code: res.code,
                  payOrderType:1
                })
                if (result.success) {
                  toPay({
                    ...result.data,
                    success: res1 => {
                      that.$navigateTo('/pagesMember/paySuccess/index?orderNo=' + that.orderNo);
                    },
                    fail: () => {
                      uni.showToast({
                        title: '支付失败',
                        icon: 'none',
                        duration: 3 * 1000
                      })
                    }
                  })
                }
              }
            },
            fail: err => {
              uni.showToast({
                title: err.errMsg || '登录获取code失败',
                icon: 'none',
                duration: 3 * 1000
              })
            }
          })
        // #endif
      },
      //公众号支付
      onBridgeReady(config) {
        const wxPayInfo = config.wxPayInfo.wxJSAPIPayInfoResponse
        window.WeixinJSBridge.invoke(
          'getBrandWCPayRequest',
          {
            appId: wxPayInfo.appId,
            timeStamp: wxPayInfo.timeStamp,
            nonceStr: wxPayInfo.nonceStr,
            package: wxPayInfo.package,
            signType: wxPayInfo.signType,
            paySign: wxPayInfo.paySign
          },
          function(res) {
            console.log('paySuccess', res, that.orderNo)
            that.$navigateTo('/pagesMember/paySuccess/index?orderNo=' + that.orderNo)
            return
          }
        )
      },
		}
	}
</script>

<style lang="scss" scoped>
.main{
  background: url('https://asset-uat.bisinuolan.cn/bixuan_uni/static/images/member/pay/top-back.png') no-repeat;
  background-size: 100% auto;
  min-height: 100%;
  padding-bottom: 118rpx;
  position: relative;
  .head-box{
    padding: 40rpx 66rpx 40rpx 40rpx;
    display: flex;
    color: #FBDBAC;
    justify-content: space-between;
    align-items: center;
    .left-box{
      display: flex;
      align-items: center;
      text{
        // margin-left: 17rpx;
        font-size: 28rpx;
      }
    }
    .right-box{
      font-size: 32rpx;
    }
  }
  .user-icon{
    border: 2rpx solid #FFFFFF;
    border-radius: 100%;
  }
  .quan-box{
    background: white;
    margin: 15rpx;
    border-radius: 5rpx;
    padding: 0rpx 44rpx 0rpx 30rpx;
    .title{
      color: #060606;
      font-size: 28rpx;
      padding: 36rpx 0rpx 20rpx;
    }
    .ticket-content{
      .ticket-box{
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx 0rpx;
        border-bottom: 2rpx solid #EEEEEE;
        &:last-child{
          border-bottom:none;
        }
        .left-box{
          display: flex;
          align-items: center;
          .price-box{
            min-width: 152rpx;
            height: 108rpx;
            flex-shrink:0;
            background: url('https://asset-uat.bisinuolan.cn/bixuan_uni/static/images/member/pay/price-back.png') no-repeat;
            background-size: 100% 100%;
            color: #FBDBAC;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 0rpx 20rpx;
            .price{
              font-size: 24rpx;
            }
            .num{
              font-size: 54rpx;
            }
          }
          .goods-box{
            margin-left: 34rpx;
            .goods-name{
              font-size: 29rpx;
              margin-bottom: 10rpx;
            }
            .goods-time{
              font-size: 24rpx;
              color: #999999;
            }
          }
        }
      }
    }
  }
}
.content-box{
  margin: 15rpx;
  background-color: white;
  border-radius: 5rpx;
  .title-box{
    font-size: 28rpx;
    padding: 34rpx 29rpx 0rpx;
  }
}
.quanyi-box{
  .title-box{
    padding: 34rpx 29rpx 0rpx;
  }
  .qy-content{
    text-align: center;
    display: flex;
    flex-wrap:wrap;
    margin-top: 40rpx;
    .qy-box{
      width: 25%;
      margin-bottom: 36rpx;
      .name{
        font-size: 26rpx;
        margin-top: 10rpx;
        color: #666666;
      }
    }
  }
}
.pay-box{
  .title-box{
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 10rpx;
    .right-box{
      .name{
        margin-right: 12rpx;
        font-size: 24rpx;
        color: #333333;
        opacity: 0.6;
      }
    }
  }
  .type-box{
    display: flex;
    padding: 51rpx 15rpx;
    margin: 0rpx 30rpx;
    justify-content: space-between;
    border-bottom: 2rpx solid #EEEEEE;
    align-items: center;
    &:last-child{
      border-bottom: none;
    }
    .left-box{
      display: flex;
      align-items: center;
      .pay-img{
        width: 50rpx;
        margin-right: 36rpx;
        max-height: 60rpx;
      }
    }
  }
}
.pay-btn{
  // height: 118rpx;
  position: fixed;
  bottom: 0rpx;
  width: 100%;
  background-color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0rpx 0rpx 10rpx #EEEEEE;
  padding: 14rpx 0rpx;
  padding-bottom: calc(14rpx + constant(safe-area-inset-bottom);
  padding-bottom: calc(14rpx + env(safe-area-inset-bottom));
  .price-box{
    margin-left: 34rpx;
    .txt1{
      font-size: 26rpx;
    }
    .txt2{
      font-size: 20rpx;
    }
    .txt3{
      font-size: 38rpx;
      font-weight: bold;
    }
  }
  .btn-box{
    font-size: 28rpx;
    background-color: #000000;
    padding: 27rpx 66rpx;
    color: white;
    margin-right: 20rpx;
    &.huise{
      background-color: #c6c6c6;
    }
  }
}
.shangpin-box{
  .good-content{
    padding: 13rpx 31rpx 0rpx;
    .good-box{
      padding: 20rpx 9rpx;
      border-bottom: 2rpx solid #EEEEEE;
      display: flex;
      align-items: center;
      .img-box{
        width: 120rpx;
        height: 120rpx;
      }
      .info-box{
        margin: 10rpx 0rpx 0rpx 45rpx;
        line-height: 1;
        flex: 1;
        width: calc(100% - 3000rpx);
        .name{
          overflow: hidden;
          text-overflow: ellipsis;
          font-size: 28rpx;
          word-break: break-all;
          white-space: nowrap;
          word-wrap:break-word;
        }
        .time{
          font-size: 24rpx;
          color: #999999;
          margin-top: 25rpx;
        }
        .price{
          margin-top: 61rpx;
          font-size: 28rpx;
          font-family: PingFang SC;
          font-weight: 400;
          color: #000000;
          line-height: 28rpx;
        }
      }
      .select-box{
        display: flex;
        align-items: center;
        padding-left: 26rpx;
      }
    }
    .good-box:last-child{
      border-bottom: none;
    }
  }
}
.boxDetails_nav{
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  position: relative
  ::v-deep{
    .nav-title{
      font-weight: bold;
    }
    .title-part{
      display: flex;
      align-items: center;
      /* #ifdef H5 */
      justify-content: center;
      /* #endif */
    }
  }
  .title-nav{
    // display: inline-block;
    // position: absolute;
    // top: 50%;
    // left: 50%;
    // transform: translate(-50%,-50%);
    display: flex;
    align-items: center;
    font-size: 32rpx;
    text-align: center;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    // padding: 20rpx 0rpx 0rpx 60rpx;
    /* #ifdef MP-WEIXIN */
    margin-left: 60rpx;
    /* #endif */
  }
  .header-left-box{
    display: flex;
    align-items: center;
  }
  .header-left {
    height: 40rpx;
    width: 40rpx;
    margin-left: 11rpx;
    /* #ifdef MP-WEIXIN */
    margin-top: 12rpx;
    /* #endif */
  }
  .header-right {
    display: flex;
    align-items: center;
    height: 100%;
    margin-right:22rpx;
    /* #ifdef MP-WEIXIN */
    padding-right: 190rpx;
    /* #endif */
  }
}
</style>
